define(function(require, exports){
	var $ = require('jquery');
	var util = require('util');
	var pubjs = require('pubjs');
	var view = require('@base/view');
	var grid  = require('@base/highGrid');
	var utilDSP = require('modules/common');
	var countSelector = require('modules/countSelector');
	var budget = require('campaign/popwin/budget');
	var batchEdit = require('campaign/popwin/batchEdit').main;
	var CampaignType = pubjs.config("CONST/CAMPAIGN_TYPE");

	var CampaignGrid = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'campaign/list',
					urlSetCharge: 'campaign/setCharge',
					param: {
						order: 'impressions|-1,clicks|-1', Type: CampaignType.RTB
					},
					cols: [
						{name:'_id',text:"ID", sort: true, align: 'center', width: 60},
						{name:'Name',text:LANG("名称"), type:'index', width: 280, render:'renderName'}
					],
					default_metrics: pubjs.config('metricsGroup/campaign/metrics'),
					// 在竞价组中有出价
					tab: pubjs.config('metricsGroup/campaign/tabs'),
					amountSubgridName: LANG('汇总'),
					hasAmountSubGrid: true,
					fireSubgridParam: true,
					needSetSubgridParam: true,
					amountSubs: ['amount_period','amount_channel','amount_region'],
					subs: [],
					subFilter: 'subFilter',
					reqType: 'websocket',
					gridName: 'campaign',
					hasTrTitle: true,
					renderTrTitle: this.renderTrTitle
				}
			);


			switch(this.parseSubsCondition(config).pop()){
				case 'platform':
				case 'spot':
					util.extend(true, config.get(), {
						'tab':{'bid': null}
					});
					break;
			}

			this.$tmpPriceData = {};
			this.Super('init', arguments);
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser('ExchangeInfo/CategoryId');
			var adx_has_pageChannel = pubjs.config('adx_has_pageChannel') || [];
			var SubChannel = data.SubChannel && data.SubChannel[0];

			// 活动类型(Channel) 1 RTB， 2监测，4 移动
			var campaignType = +data.Channel;

			util.each(subs, function(sub){
				// 区分RTB活动和监测活动
				if(sub.type === 'mediaAndAd' || sub.type === 'mediaAndAd_lite'){
					sub.iconBtn.toggle(campaignType== 1 || campaignType== 4);
				}
				if(sub.type === 'mediaAndAd_Monitor'){
					sub.iconBtn.toggle(campaignType == 2);
				}
				if(sub.type === 'channelCategory')
				{
					sub.iconBtn.toggle(adx_has_pageChannel.indexOf(SubChannel) != -1)
				}
				if(sub.type === 'people')
				{
					sub.iconBtn.toggle(campaignType== 1 || campaignType== 4);
				}
			});
		},
		// 行title属性渲染函数
		renderTrTitle: function(data, tr){
			if(data._id && data.Name){
				return data._id + '：' + data.Name;
			}else{
				return '';
			}
		},
		renderName: function(i, val, data, con, tr){
			/**
				Status：
				1 正常/进行中
				2 暂停
				3 草稿
				4 未开始
				5 已结束
				6 超预算
			**/
			var icon = [
				['close', LANG('关闭')],
				['running', LANG('进行中')],
				['pause', LANG('已暂停')],
				['draft', LANG('草稿')],
				['notStart ', LANG('未开始')],
				['completed', LANG('已结束')],
				['overBudget', LANG('超预算')],
				['deleted', LANG('已归档')]
			];

			// 暂时去掉其他状态
			// var num = 0;
			// var start = data['StartTime'];
			// var end = data['EndTime'];
			// var now = util.date('Ymd', new Date());
			// if (start > now) {
			// 	num =  4;		//未开始
			// }
			// if (start <= now && (+end === 0 || end >= now) ) {
			// 	if (data['BudgetExceed']) {
			// 		num =  6;		//超预算
			// 	} else {
			// 		num =  1;		//进行中
			// 	}
			// }
			// if (+end !== 0 &&  end < now) {
			// 	num =  5;			//已结束
			// }
			// if (data['Status'] == 2) {
			// 	num = 2;
			// }

			var num = data.Status;
			num = (data.IsDeleted && 7) || (data.IsDraft && 3) || num || 0;

			var status = icon[num];

			// 名称点击跳转编辑
			var editAction = '';
			if(utilDSP.isBrandVersion()){
				editAction = '#serving/campaign' + utilDSP.getBrandSearch({'campaignId': data._id});
			}else{
				editAction = '#campaign/edit/' + data._id;
			}

			if(this.$isRm === undefined)
			{
				var user = pubjs.getUser();
				user = user && user.current;
				this.$isRm = !!(user && user.ReachMax && user.ReachMax.Open);
			}

			if(this.$isRm === true && data.ReachMax && data.ReachMax.hasOwnProperty('CCode'))
			{
				switch (data.ReachMax.CCode)
				{
					// done
					case 1:
						val = `【RM审核状态: 成功】${val}`;
						break;
					//fail
					case 2:
						val = `【RM审核状态: 失败, 原因: ${data.ReachMax.CMsg}】${val}`;
						break;
					//ing
					case 3:
						val = `【RM审核状态: 审核中】${val}}`;
						break;
				}
			}

			var name = $('<a class="text-truncate dib"/>').attr({
				// 'target': '_blank',
				'href': editAction
			}).text(LANG(val)).css({
				'vertical-align': 'middle'
			}).width(con.width-45);

			var html = $('<div class="tl fl mr10" title="'+ LANG(val) +'"><i title="'+status[1]+'" class="status status-'+status[0]+' mr5"></i>'+'</div>').append(name);
			if (data.Channel !== 2) {
				var icon_all = html.find('i').addClass('cur_p');
				this.uiBind(icon_all, 'click', data, this.showBudgetPopwin);
			}

			return html;
		},
		renderPrice: function(i, val, row, con){
			//监测广告位 没有编辑出价
			if(+row.Channel === 2){
				return '-';
			}
			//计费方式
			var value = (!row.WardenStatus ? val : row.TargetCpa),
				data = {
					'Price'			: value,
					'CampaignId'	: row._id,
					'WardenStatus'	: row.WardenStatus
				};
			value = this.formatCurrency(value);

			// 暂时没有只读状态
			/*
			//用户是只读状态 只显示价格 不能编辑
			var userStatus = pubjs.getUser().current.Status;
			if(+userStatus === 1){
				return value;
			}
			*/
			var iconMap = ['editCPM', 'editCPA', 'editCPC', 'editCOM'];
			var dom = $([
				'<div class="uk-text-truncate">',
					'<i class="status status-'+ iconMap[row.WardenStatus] +' mr5"></i>'+ value,
				'</div>'
				].join(''));
			this.uiBind(dom.find('i'), 'click', data, 'eventChangeTopPrice');
			return dom;
		},
		eventChangeTopPrice: function(ev, elm){
			this.$tmpPriceData = ev.data;
			var topPriceMod = this.$.changeTopPrice;

			if(!topPriceMod){
				topPriceMod = this.create('changeTopPrice', countSelector.base, {
					prefix: "￥",		//字段前缀
					suffix: LANG('元'),//字段后缀
					addCount: 0.5,
					value: this.$tmpPriceData.Price
				});
			}

			topPriceMod.show({
				anchor:$(elm).offset(),
				data: this.$tmpPriceData.Price
			});

			return false;
		},
		formatCurrency: function(val){
			val = util.round0(val, 2);
			return (LANG("￥"))+util.numberFormat(val);
		},
		onUpdateValue: function(ev){
			var WardenStatus = this.$tmpPriceData.WardenStatus;
			if(+ev.param < 0){
				pubjs.alert(LANG('价格必须为一个正数'));
				return false;
			}

			if(!util.isNumber(+ev.param)){
				pubjs.alert(LANG('价格信息错误'));
				return false;
			}

			var data = {
				'TargetCpa': WardenStatus ? ev.param : 0,
				'TopPrice': WardenStatus ? 0 : ev.param,
				'WardenStatus': WardenStatus,
				'ids': [this.$tmpPriceData.CampaignId]
			};
			var url = this.getConfig('urlSetCharge');
			pubjs.mc.send(url, data, this.onSaveValue.bind(this));
			if(this.$.changeTopPrice){
				this.$.changeTopPrice.destroy();
			}
			return false;
		},
		onSaveValue: function(err, data){
			if(err){
				pubjs.alert(err.message);
			}
			pubjs.alert(LANG('修改成功'));
			this.reload();
			this.$tmpPriceData = {};
		},
		showBudgetPopwin: function(evt, elm){
			// var data = evt.data;
			// if(!this.$.budgetPopwin) {
			// 	this.create('budgetPopwin', budget.campaignBudget, {});
			// }

			// this.$.budgetPopwin.update({
			// 	'anchor': $(elm)
			// }).setData(data).show();

			var data = evt.data;
			var title = LANG('修改预算');
			var type = 'limit';
			var mod = this.$.batchEdit;
			if (!mod)
			{
				mod = this.create('batchEdit', batchEdit, {
					types: {
						limit: {
							module: 'plan/modules/limit.batchEdit',
							url: 'campaign/setBudget'
						}
					}
				});
			}
			mod.reset().show().setTitle(title).setType(type).setParam([data._id]).setData(data.MainStrategy || {});
		}
	});
	exports.base = CampaignGrid;

	// 子表格活动列表
	var SubCampaignGrid = CampaignGrid.extend({
		init: function(config){
			config = pubjs.conf(config, {
					subs: [
						'mediaAndAd','mediaAndAd_Monitor',
						'sweety','whisky',
						'period','frequency','region',
						'client','product'
					]
				}
			);

			this.Super('init', arguments);
		}
	});
	exports.subBase = SubCampaignGrid;
	var FREQUENCY_MAP = { //频次控制_过滤类型
		 0: LANG('活动'),
		1: LANG('产品'),
		2: LANG('创意'),
		3: LANG('创意包'),
		4: LANG('计划')
	};

	var FREQUENCY_PERIOD_MAP = { //频次控制_周期
		0: LANG('每周'),
		1: LANG('每小时'),
		2: LANG('每天'),
		3: LANG('每月'),
		4: LANG('每半年')
	};

	var SubGrid = view.container.extend({
		init: function (config) {
			config = pubjs.conf(config, {
				view_model: {
					'time': ''
					,'frequency': []
					,'totalLimit': ''
					,'dailyLimit': ''
					,'vmEdit': this.vmEdit
				}
			});
			this.Super('init', arguments);
		}
		, afterBuild: function () {
			var self = this;
			var c = self.getConfig();
			var el = self.getDOM();
			var condition = c.param && c.param.condition;
			var plan_id;
			if(condition && condition.indexOf('plan_id'))
			{
				try
				{
					condition = JSON.parse(condition);
					util.each(condition, function(item) {
						if(item && item.plan_id)
						{
							plan_id = +item.plan_id;
						}
					});
				}
				catch(e)
				{
					plan_id = 0;
				}
			}

			var config = {grid: c};
			if(plan_id)
			{
				this.$planId = plan_id;
				this.append(`
					<div>
						<hr style="height:1px;border:none;border-top:1px solid #e9e9e9;margin-bottom:0;" />
						<div class="P-campaignSubGrid">
							<div class="planEdit" ms-click="vmEdit('time')">
								<i class="main-icon icon-time fl"></i>
								<i class="status icon-edit fr"></i>
								<div class="title">${LANG('计划时间:')}</div>
								<div class="content mt10">{{time}}</div>
							</div>
							<div class="planEdit" ms-click="vmEdit('frequency')">
								<i class="main-icon icon-frequency fl" style="font-size:23px"></i>
								<i class="status icon-edit fr"></i>
								<div class="title">${LANG('计划频次:')}</div>
								<div class="content mt10" ms-repeat-item="frequency">{{item}}</div>
							</div>
							<div class="planEdit" ms-click="vmEdit('limit')">
								<div class="fl" style="margin-right:40px;">
									<i class="main-icon icon-rise fl"></i>
									<div>
										<div class="title fl">${LANG('计划总上限:')}</div>
										<div class="clearfix"></div>
									</div>
									<div>
										<div class="content mt10 fl">{{totalLimit}}</div>
										<div class="clearfix"></div>
									</div>
								</div>
								<div class="fl">
									<i class="status icon-edit fr"></i>
									<div>
										<div class="title fl">${LANG('计划每日上限:')}</div>
										<div class="clearfix"></div>
									</div>
									<div>
										<div class="content mt10 fl">{{dailyLimit}}</div>
										<div class="clearfix"></div>
									</div>
								</div>
							</div>
							<div class="clearfix"></div>
						</div>
						<div class="M-formHead">
							<span class="ml10" pub-name="add" pub-mod="@base/common/drop.add"/>
						</div>
					</div>
					`);

				var options = [];
				if(pubjs.checkRight('campaign.add'))
				{
					options.push({
						'id': 1,
						'name': LANG('新建推广组'),
						'href':"#campaign/edit?planId=" + plan_id,
						'target':"_blank"
					});
				}

				config.add = {
					'def': LANG(''),
					'options': options
				};

				self.reloadInfo();
				self.createAsync('batchEdit', 'campaign/popwin/batchEdit.main', {
					types: {
						date: {
							url: 'plan/setPeriod'
						},
						frequency: {
							url: 'plan/setFrequency'
						},
						limit: {
							module: 'plan/modules/limit.batchEdit',
							url: 'plan/setLimit'
						}
					}
				});
			}

			this.append($([
				'<div class="" pub-name="grid" pub-mod="campaign/grid/campaign.subBase"/>'
			].join('')));

			this.buildFromTemplate(config);
		}
		,afterInfo: function(err, data)
		{
			if(err)
			{
				return pubjs.alert(err.message);
			}

			this.setPlanData(data);
		}
		,setPlanData: function(data)
		{
			var vm = this.vm.$;
			this.$planData = data;
			if(data)
			{
				vm.time = `${data.StartTime} ${LANG('至')} ${data.EndTime || LANG('不限')}`;
				var frequency = [];
				if(data.FrequencyFilters && data.FrequencyFilters.length)
				{
					util.each(data.FrequencyFilters, function(item)
					{
						frequency.push(`${FREQUENCY_MAP[item.Type]}
						${FREQUENCY_PERIOD_MAP[item.Period]}
						${LANG('展现不超过')} ${item.Frequency} ${LANG('次')}`);
					});
				}

				vm.frequency = frequency || '-';
				var limit_str = [];
				util.each([data.TotalLimit, data.DailyLimit], function(limit) {
					limit_str.push(`${LANG('预算')} ${util.numberFormat(limit.Budget)} ${LANG('元')}
						${LANG('曝光%1千次',limit.Impression)} ${LANG('点击%1 次', limit.Click)}
					`);
				});

				vm.totalLimit = limit_str[0];
				vm.dailyLimit = limit_str[1];
			}
		}
		,reloadInfo: function()
		{
			if(this.$planId)
			{
				pubjs.mc.send('plan/info', {_id: this.$planId}, this.afterInfo.bind(this));
			}

			if(this.$ && this.$.grid)
			{
				this.$.grid.load()
			}

			return this;
		}
		,vmEdit: function(module)
		{
			var title, type;
			switch(module)
			{
				case 'time':
					title = LANG('投放日期');
					type = 'date';
					break;
				case 'frequency':
					title = LANG('频次控制');
					type = 'frequency';
					break;
				case 'limit':
					title = LANG('修改上限');
					type = 'limit';
					break;
			}

			this.$.batchEdit.reset().show().setTitle(title).setType(type).setParam([this.$planId]).setData(this.$planData);
		}
		,onBatchEditSuccess: function(ev)
		{
			this.reloadInfo();
			return false;
		}
	});

	exports.subGrid = SubGrid;

});